package cn.ug.activity.web.controller;

import cn.ug.activity.bean.ActivityInfoBean;
import cn.ug.activity.bean.CertificateBean;
import cn.ug.activity.bean.DisplayLinkParamBean;
import cn.ug.activity.mapper.entity.Contract;
import cn.ug.activity.service.ActivityInfoService;
import cn.ug.activity.service.ContractService;
import cn.ug.activity.web.utils.ESignHelper;
import cn.ug.activity.web.utils.UploadUtil;
import cn.ug.aop.RequiresPermissions;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.AplicationResourceProperties;
import cn.ug.core.SerializeObjectError;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.Auth;
import com.timevale.esign.sdk.tech.bean.result.AddSealResult;
import com.timevale.esign.sdk.tech.bean.result.FileDigestSignResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ug.util.ConstantUtil.SLASH;

@RestController
@RequestMapping("infos")
public class ActivityInfoController extends BaseController {
    @Autowired
    private ActivityInfoService activityInfoService;
    @Autowired
    protected AplicationResourceProperties properties;
    @Autowired
    private ContractService contractService;

    @GetMapping(value = "/{id}")
    public SerializeObject get(@RequestHeader String accessToken, @PathVariable String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        ActivityInfoBean entity = activityInfoService.get(id);
        if(null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @GetMapping(value = "/esign/test")
    public SerializeObject test() {
        ESignHelper.initProject(properties.getProjectId(), properties.getProjectSecret(), properties.getApiUrl());
        String  accountId = ESignHelper.createPersonAccount("13094818226", "张小庆", "412828198706243739");
        String organId = ESignHelper.createOrganizeAccount(properties.getOrganName(), properties.getOrganCode(), properties.getLegalName(), properties.getLegalIdcard());
        AddSealResult userPersonSealData = ESignHelper.addPersonTemplateSeal(accountId);
        ESignHelper.addOrganizeTemplateSeal(organId, "", properties.getLowboomText());


        Map<String, Object> map = new HashMap<>();
        map.put("companyName", properties.getOrganName());
        map.put("address", properties.getAddress());
        map.put("legalPerson", properties.getLegalName());
        map.put("userName", "张小庆");
        map.put("idcard", "412828198706243739");
        map.put("mobile", "13094818226");
        map.put("productName", "新手体验1二1期");
        map.put("totalGram", "2");
        map.put("specification", "2");
        map.put("price", "275.23");
        map.put("totalAmount", "550.46");
        map.put("year", "2018");
        map.put("month", "4");
        map.put("day", "23");
        FileDigestSignResult userPersonSignResult = ESignHelper.padData(ESignHelper.getBytes(properties.getTemplateUrl()+"/template.pdf"), accountId, userPersonSealData.getSealData(), map);
        FileDigestSignResult platformSignResult = ESignHelper.platformSignByStreamm(userPersonSignResult.getStream());
        if (0 == userPersonSignResult.getErrCode()) {
            String signServiceId = userPersonSignResult.getSignServiceId();
            String orderId = "kyling0015";
            String fileName = orderId+".pdf";
            String filePath = properties.getTemplateUrl() + SLASH + fileName;
            ESignHelper.saveSignedByStream(platformSignResult.getStream(), properties.getTemplateUrl(), fileName);

            String url = UploadUtil.upload(properties.getAccessKey(), properties.getSecretKey(), properties.getBucket(), filePath, fileName , properties.getFileDomain());
            String businessTempletId = ESignHelper.createIndustryType(properties.getProjectId(), properties.getProjectSecret(), properties.getIndustry(), properties.getBusTypeUrl());
            String sceneTempletId = ESignHelper.createSceneType(properties.getProjectId(), properties.getProjectSecret(), businessTempletId, properties.getScene(), properties.getSceneTypeUrl());
            String segmentTempletId = ESignHelper.createSegmentType(properties.getProjectId(), properties.getProjectSecret(), sceneTempletId, properties.getSegment(), properties.getSegTypeUrl());
            DisplayLinkParamBean displayLinkParamRealName1 = new DisplayLinkParamBean();
            displayLinkParamRealName1.setDisplayName("甲方");
            displayLinkParamRealName1.setParamName("realName1");

            DisplayLinkParamBean displayLinkParamUserName1 = new DisplayLinkParamBean();
            displayLinkParamUserName1.setDisplayName("住址");
            displayLinkParamUserName1.setParamName("userName1");

            DisplayLinkParamBean displayLinkParamRealName2 = new DisplayLinkParamBean();
            displayLinkParamRealName2.setDisplayName("乙方");
            displayLinkParamRealName2.setParamName("realName2");

            DisplayLinkParamBean displayLinkParamUserName2 = new DisplayLinkParamBean();
            displayLinkParamUserName2.setDisplayName("身份证号码");
            displayLinkParamUserName2.setParamName("userName2");

            ArrayList<DisplayLinkParamBean> segmentProp = new ArrayList<DisplayLinkParamBean>();
            segmentProp.add(displayLinkParamRealName1);
            segmentProp.add(displayLinkParamUserName1);
            segmentProp.add(displayLinkParamRealName2);
            segmentProp.add(displayLinkParamUserName2);
            ESignHelper.createSegmentPropType(properties.getProjectId(), properties.getProjectSecret(), segmentTempletId, segmentProp, properties.getSegpropUrl());
            String sceneEvId = ESignHelper.createChainOfEvidence(sceneTempletId, "新手体验1期购买协议", properties.getProjectId(), properties.getProjectSecret(), properties.getVoucherUrl());
            JSONObject segmentDataJSON = new JSONObject();
            segmentDataJSON.put("realName1", "杭州柚高网络信息有限公司");
            segmentDataJSON.put("userName1", "http://www.u-gold.cn");
            segmentDataJSON.put("realName2", "13094818226");
            segmentDataJSON.put("userName2", "张小庆");
            String segmentData = segmentDataJSON.toString();
            JSONObject result = ESignHelper.createSegmentOriginalStandard(properties.getProjectId(), properties.getProjectSecret(), segmentData, filePath, segmentTempletId, properties.getSimulateUrl());
            String evId = result.getString("evid");
            String fileUploadUrl = result.getString("url");
            ESignHelper.uploadOriginalDocumen(evId, fileUploadUrl, filePath);
            ESignHelper.appendEvidence(properties.getProjectId(), properties.getProjectSecret(), sceneEvId, evId, properties.getAppendVoucherUrl(), signServiceId);

            List<CertificateBean> certificates = new ArrayList<CertificateBean>();
            CertificateBean personBean = new CertificateBean();
            personBean.setName(properties.getOrganName());
            personBean.setType("CODE_USC");
            personBean.setNumber(properties.getOrganCode());
            CertificateBean orgBean = new CertificateBean();
            orgBean.setName("张小庆");
            orgBean.setType("ID_CARD");
            orgBean.setNumber("412828198706243739");

            certificates.add(personBean);
            certificates.add(orgBean);
            ESignHelper.relateSceneEvIdWithUser(properties.getProjectId(), properties.getProjectSecret(), sceneEvId, certificates, properties.getRelateUrl());
            String esignUrl = ESignHelper.getViewCertificateInfoUrl(properties.getProjectId(), properties.getProjectSecret(), sceneEvId, "412828198706243739", properties.getViewpageUrl());
            Contract contract = new Contract();
            contract.setOrderId(orderId);
            contract.setOriginalUrl(url);
            contract.setThirdpartyUrl(esignUrl);
            contractService.save(contract);
        }
        return new SerializeObject<>(ResultType.NORMAL, "success");
    }

    @RequiresPermissions("activity:info:save")
    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, ActivityInfoBean entity) {
        if(null == entity || StringUtils.isBlank(entity.getName())) {
            return new SerializeObjectError("22000001");
        }

        if (activityInfoService.save(entity)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @RequiresPermissions("activity:info")
    @GetMapping(value = "/list")
    public SerializeObject<DataTable<ActivityInfoBean>> list(@RequestHeader String accessToken, Page page, String name, String startDate, String endDate) {
        name = UF.toString(name);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = activityInfoService.countRecords(name, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<ActivityInfoBean> list = activityInfoService.listRecords(name, startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<ActivityInfoBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<ActivityInfoBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<ActivityInfoBean>()));
    }
}
